package com.anche.cywebnew.Service.systemManager.Impl;

import cn.hutool.core.date.DateUtil;
import com.anche.cywebnew.DAO.configManager.SysOptionMapper;
import com.anche.cywebnew.DAO.systemManager.TerminalMapper;
import com.anche.cywebnew.DAO.systemManager.UserMapper;
import com.anche.cywebnew.Pojo.systemManager.SysUser;
import com.anche.cywebnew.Pojo.systemManager.TerminalInfo;
import com.anche.cywebnew.Service.securityManager.SecurityLogService;
import com.anche.cywebnew.Service.systemManager.LoginService;
import com.anche.cywebnew.Utils.ResponseBody.ResponseResult;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private TerminalMapper terminalMapper;

    @Autowired
    private SysOptionMapper optionMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SecurityLogService securityLogService;

    @Override
    public ResponseResult chekUserState(SysUser sysuser) {
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode("1");
        responseResult.setMessage("用户状态正常");
        try {
            //账户状态
            if (sysuser.getStatus() == 2 && null != sysuser.getStatus()) {
                responseResult.setCode("0");
                responseResult.setMessage("帐号锁定中，请联系管理员解锁后再试");
                return responseResult;
            }
            if (null != sysuser.getStatus() && sysuser.getStatus().equals(1)) {
                responseResult.setCode("0");
                responseResult.setMessage("帐号处于停用状态，请联系管理员！");
            }
            return responseResult;
        } catch (Exception e) {
            e.printStackTrace();
            responseResult.setCode("0");
            responseResult.setMessage("状态验证有问题，联系管理员msg:" + e.getMessage());
            return responseResult;
        }
    }

    @Override
    public ResponseResult checkWorkTime(SysUser sysuser) {
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode("1");
        responseResult.setMessage("正常工作时间");
        try {
            // 非工作时间段登录
            if (null != sysuser.getDaystart() && null != sysuser.getDayend()) {
                SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");
                Date start = sdf.parse(sysuser.getDaystart());
                Date end = sdf.parse(sysuser.getDayend());
                Date now = new Date();
                now = sdf.parse(sdf.format(now));
                if (!(now.after(start) && now.before(end))) {
                    responseResult.setCode("0");
                    responseResult.setMessage("用户" + sysuser.getLoginname() + "登录时，超出工作时间");
                    securityLogService.insertSecurityLog("用户登录", "用户【" +  sysuser.getLoginname() + "】非工作时间登录", sysuser);
                }
            } else {
                responseResult.setCode("0");
                responseResult.setMessage("工作时间设置有问题，联系管理员");
            }
            return responseResult;
        } catch (Exception e) {
            e.printStackTrace();
            responseResult.setCode("0");
            responseResult.setMessage("工作时间验证有问题，联系管理员msg:" + e.getMessage());
            return responseResult;
        }
    }

    @Override
    public ResponseResult checkRangeIP(SysUser sysuser, String ip) {
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode("1");
        try {
            if (null != sysuser.getIps() && !sysuser.getIps().equals("")) {
                if (sysuser.getIps().indexOf(ip) >= 0) {
                    responseResult.setMessage("终端验证成功");
                } else {
                    responseResult.setCode("0");
                    responseResult.setMessage("终端识别号" + ip == null ? "" : ip + "不在范围内");
                }
            } else {
                responseResult.setCode("0");
                responseResult.setMessage(sysuser.getLoginname() + "用户未设置IP集，请联系管理员！");
            }
            return responseResult;
        } catch (Exception e) {
            e.printStackTrace();
            responseResult.setCode("0");
            responseResult.setMessage("限制IP验证有问题，联系管理员msg:" + e.getMessage());
            return responseResult;
        }
    }

    @Override
    public ResponseResult checkBlackIP(String ip) {
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode("1");
        TerminalInfo terminalInfo = new TerminalInfo();
        Date dateNow = new Date();
        try {
            terminalInfo = terminalMapper.getTerminalByIP(ip);
            if (null != terminalInfo) {
                if (terminalInfo.getIslocked().equals("1")) {
                    Date sockDate = terminalInfo.getLockedtime();
                    //sockDate = sdf.parse(sdf.format(sockDate));
                    if (dateNow.after(sockDate)) {
                        terminalInfo.setIslocked("0");
                        terminalInfo.setUpdate_time(dateNow);
                        terminalInfo.setFail_times(0);
                        terminalInfo.setJyw(DigestUtils.md5Hex("" + terminalInfo.getTerminal_id() + terminalInfo.getIslocked()));
                        terminalMapper.updateTerminalByIP(terminalInfo);
                        terminalMapper.clearLockTimeByIP(terminalInfo.getTerminal_id());
                        responseResult.setMessage("此IP锁定时间已过，已自动踢出黑名单。");
                    } else {
                        String mString = String.format("此IP被记入黑名单,请联系管理员解锁或等待%s分钟后自动解锁！", (sockDate.getTime() - dateNow.getTime()) / 1000 / 60);
                        responseResult.setCode("0");
                        long unlocktime = (sockDate.getTime() - dateNow.getTime()) / 1000;
                        responseResult.setObj(unlocktime);
                        responseResult.setMessage(mString);
                    }
                } else {
                    terminalInfo.setIslocked("0");
                    terminalInfo.setUpdate_time(dateNow);
                    terminalInfo.setFail_times(0);
                    terminalInfo.setJyw(DigestUtils.md5Hex("" + terminalInfo.getTerminal_id() + terminalInfo.getIslocked()));
                    terminalMapper.updateTerminalByIP(terminalInfo);
                    responseResult.setMessage("IP限制正常");
                }
            } else {
                responseResult.setMessage("IP限制正常");
            }
            return responseResult;
        } catch (Exception e) {
            e.printStackTrace();
            responseResult.setCode("0");
            responseResult.setMessage("IP黑名单检测异常，联系管理员msg:" + e.getMessage());
            return responseResult;
        }
    }

    @Override
    public ResponseResult checkUserData(SysUser sysuser) {
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode("1");
        try {
            if (null != sysuser.getJyw() && !sysuser.getJyw().equals("")) {
                System.out.println(DigestUtils.md5Hex(sysuser.getLoginname() + sysuser.getName() + sysuser.getSfzhm() + sysuser.getStatus()));
                if (sysuser.getJyw().equals(DigestUtils.md5Hex(sysuser.getLoginname() + sysuser.getName() + sysuser.getSfzhm() + sysuser.getStatus()))) {
                    responseResult.setMessage("用户关键数据正常！");
                    responseResult.setCode("1");
                } else {
                    responseResult.setMessage("用户关键数据被篡改！" + DigestUtils.md5Hex(sysuser.getLoginname() + sysuser.getName() + sysuser.getSfzhm() + sysuser.getStatus()));
                    responseResult.setCode("0");
                }
            } else {
                responseResult.setMessage("用户数据校验位为空！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            responseResult.setCode("0");
            responseResult.setMessage("用户数据校验异常:" + e.getMessage());
            return responseResult;
        }
        return responseResult;
    }

    @Override
    public String LockMsg(Integer errorTimes, SysUser sysUser) {
        String ret = "";
        String times = optionMapper.getOptionValue("安全策略", "UserFailLoginTimes", "1");
        times = times != null && !times.equals("") ? times : "5";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
        String sdsj = formatter.format(new Date());// 获得锁定时间,以便写入日志里
        if (errorTimes >= Integer.valueOf(times)) {
            if (sysUser != null) {
                //0:正常   2:锁定
                sysUser.setStatus(2);
                securityLogService.insertSecurityLog("用户锁定", "用户【" +  sysUser.getLoginname() + "】锁定", sysUser);
            }
        }
        if (sysUser != null) {
            sysUser.setErrortimes(errorTimes);
            String jyw = DigestUtils.md5Hex(sysUser.getLoginname() + sysUser.getName() + sysUser.getSfzhm() + sysUser.getStatus());
            sysUser.setJyw(jyw);
            userMapper.userFailLogin(sysUser);
        }
        if (errorTimes > 0 && errorTimes < Integer.valueOf(times)) {
            ret = String.format("登录失败%s次，再失败%s次此账号将会被锁定。   ", errorTimes.toString(),
                    String.valueOf(Integer.valueOf(times) - errorTimes));
        } else if (errorTimes >= Integer.valueOf(times)) {
            ret = String.format("登录失败%s次，帐号被锁定。   ", errorTimes.toString());
        }
        return ret;
    }

    @Override
    public String IPLockMsg(int ipTimes, TerminalInfo terminalInfo, SysUser sysUser) {
        String ret = "";
        String IPTimes = optionMapper.getOptionValue("安全策略", "TerminalFailLoginTimes", "1");//TerminalFailLoginTimes
        String time = optionMapper.getOptionValue("安全策略", "TerminalLockTime", "1");
        IPTimes = IPTimes != null && !IPTimes.equals("") ? IPTimes : "7";
        time = time != null && !time.equals("") ? time : "30";
        Date date = new Date();

        if (ipTimes >= Integer.valueOf(IPTimes)) {
            if (terminalInfo != null) {
                //0:未锁定   1:已锁定
                terminalInfo.setIslocked("1");
                long currentTime = System.currentTimeMillis();
                currentTime += 30 * 60 * 1000;
                Date lockdate = new Date(currentTime);
                terminalInfo.setLockedtime(lockdate);
                securityLogService.insertSecurityLog("终端锁定",  "终端【" +  terminalInfo.getTerminal_id() + "】锁定", sysUser);
            }
        }
        if (terminalInfo != null) {
            terminalInfo.setFail_times(ipTimes);
            terminalInfo.setUpdate_time(date);
            String jyw = DigestUtils.md5Hex("" + terminalInfo.getTerminal_id() + terminalInfo.getIslocked());
            terminalInfo.setJyw(jyw);
            terminalMapper.updateTerminalByIP(terminalInfo);
        }
        if (ipTimes > 0 && ipTimes < Integer.valueOf(IPTimes)) {
            ret = String.format("  IP登陆失败%s次,再失败%s次IP将会被锁定%s分钟", ipTimes, String.valueOf(Integer.valueOf(IPTimes) - ipTimes), time);
        } else if (ipTimes >= Integer.valueOf(IPTimes)) {
            ret = String.format("  IP登录失败%s次，IP被锁定，请%s分钟后再试", ipTimes, (terminalInfo.getLockedtime().getTime() - new Date().getTime()) / 1000 / 60);
        }
        return ret;
    }


}
